package mnet

/*
 * rpc handler
 */
import "reflect"

type RPCMessageHandler struct {
	Dealer map[string]reflect.Value
}

// BuildStructMethods struct object function and return
func (rmd *RPCMessageHandler) BuildStructMethods(structObj interface{}) {
	rmd.Dealer = make(map[string]reflect.Value)
	vf := reflect.ValueOf(structObj)
	vft := vf.Type()
	num := vf.NumMethod()
	for i := 0; i < num; i++ {
		rmd.Dealer[vft.Method(i).Name] = vf.Method(i)
	}
}

// Process calls local function.
func (rmd *RPCMessageHandler) Process(s *Session, methodName string, para ...interface{}) {
	RunWithoutPanic(func() {
		if handler, ok := rmd.Dealer[methodName]; ok {
			var paras []reflect.Value = make([]reflect.Value, 0, len(para)+1)
			paras = append(paras, reflect.ValueOf(s))
			for i := 0; i < len(para); i++ {
				paras = append(paras, reflect.ValueOf(para[i]))
			}
			handler.Call(paras)
		} else {
			log().Error("[net] can not find ", methodName, " dealer")
		}
	})
}
